package com.tju.resource.oauth.controller.tb;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.tju.resource.annotation.Log;
import com.tju.resource.business.tb_impl_order.report.TbImplReportOrderService;
import com.tju.resource.result.ResultEnum;
import com.tju.resource.result.ResultUtil;
import com.tju.resource.tool.enum_utils.FunctionType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@RestController
public class TbImplOrderReportController {

    private static final String prefix = "implrepo";

    @Autowired
    TbImplReportOrderService tbImplReportOrderService;

    @PostMapping(prefix + "/export")
    @Log(type= FunctionType.Export)
    @PreAuthorize("hasAuthority('sys:cons:construction:export')")
    public void export(@RequestBody JSONObject params, HttpServletResponse response) {
        try {
            OutputStream writer = response.getOutputStream();

            response.setContentType("application/octet-stream; charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode("ImplOrd" + Math.random() + ".xls", StandardCharsets.UTF_8));

            try {
                Method method = tbImplReportOrderService.getClass().getMethod(params.getStr("REPO_TYPE"), JSONObject.class, OutputStream.class);
                boolean fillRet = (boolean) method.invoke(tbImplReportOrderService, params, writer);

                if (!fillRet) {
                    throw new Exception("Unknown Error");
                }

            } catch (NoSuchMethodException e404) {
                e404.printStackTrace();
                response.setStatus(404);
                writer.write(JSONUtil.parseObj(ResultUtil.error(ResultEnum.UNKONW_ERROR, "不支持的报表类型!")).toJSONString(0).getBytes());
            } catch (Exception e) {
                e.printStackTrace();
                response.setStatus(500);
                writer.write(JSONUtil.parseObj(ResultUtil.error(ResultEnum.UNKONW_ERROR, e.toString())).toJSONString(0).getBytes());
            } finally {
                writer.flush();
                writer.close();
            }
        } catch (Exception e) {
//            return ResultUtil.error(ResultEnum.UNKONW_ERROR, e.toString());
        }
    }


}
